package com.ruoyi.camera.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApiService {
    private static final Logger logger = LoggerFactory.getLogger(ApiService.class);

    @Value("${api.base-url}")
    private String baseUrl;

    private final RestTemplate restTemplate;

    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 获取原始响应
     * * @author xhl
     * @return
     */
    public Map<String, Object> getRawResponse() {
        String url = baseUrl + "login";
        // 创建请求头
        HttpHeaders headers = new HttpHeaders();
        // 创建请求体
        Map<String, Object> body = new HashMap<>();
        body.put("language", 0);
        body.put("user", "admin");
        body.put("passwd", "d47bd8f7b4c6f0dac0a1345b454e1d3d");

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(body, headers);

        // 发送POST请求并接收响应
        ResponseEntity<Map> response = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);

        // 直接返回原始响应体中的所有内容
        return response.getBody();
    }

    /**
     * 获取Token
     * * @author xhl
     * @return
     */
    public Map<String, Object> getToken() {
        try {
            Map<String, Object> rawResponse = getRawResponse();
            if (rawResponse == null) {
                throw new RuntimeException("从service收到null response");
            }
            // 确保 resCode 是整数类型
            Integer resCode = (Integer) rawResponse.get("resCode");
            String resMsg = (String) rawResponse.get("resMsg");

            if (resCode != null && resCode == 0) {
                Map<String, Object> resData = (Map<String, Object>) rawResponse.get("resData");
                if (resData == null) {
                    throw new RuntimeException("在response中缺少resData");
                }
                String token = (String) resData.get("token");
                if (token == null || token.isEmpty()) {
                    throw new RuntimeException("resData中找不到Token或为空");
                }
                // 将 token 添加到返回的 map 中以便后续使用
                rawResponse.put("token", token);
                return rawResponse;
            } else {
                throw new RuntimeException(String.format("获取token失败: %s", resMsg));
            }
        } catch (Exception e) {

            e.printStackTrace();
            throw new RuntimeException("获取token时发生意外错误", e);
        }
    }
    /**
     * 查询设备状态
     * * @author xhl
     * @param token
     * @return
     */
    public Map<String, Object> queryDeviceStatus(String token) {
        String url = baseUrl + "queryDeviceStatus";

        // 创建请求头，包括必要的授权信息
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + token);

        HttpEntity<String> entity = new HttpEntity<>("", headers);

        ResponseEntity<Map> response = restTemplate.exchange(
                url,
                HttpMethod.POST,
                entity,
                Map.class
        );

        if (response.getStatusCode().is2xxSuccessful()) {
            return response.getBody(); // 返回完整的响应体
        } else {
            throw new RuntimeException("Failed to query device status");
        }
    }

    /**
     * 摄像机管理
     * @author xhl
     * @param token
     * @param cameraType 相机类型
     * @return
     */
    public Map<String, Object> queryCameraChannel(String token, Integer cameraType) {
        String url = baseUrl + "queryCameraChannel";
        // 创建请求头，包括必要的授权信息
        HttpHeaders headers = new HttpHeaders();
        headers.set("Token", token);
        headers.set("Content-Type", "application/json");

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (cameraType != null) {
            builder.queryParam("cameraType", cameraType);
        }

        HttpEntity<?> entity = new HttpEntity<>(headers);

        try {
            ResponseEntity<Map> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.GET,
                    entity,
                    Map.class
            );
            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> responseBody = response.getBody();

                // 检查返回的数据是否与请求的 cameraType 匹配
                /*if (cameraType != null && responseBody.containsKey("resData") &&
                    responseBody.get("resData") instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> resData = (Map<String, Object>) responseBody.get("resData");

                    List<Map<String, Object>> channelList = (List<Map<String, Object>>) resData.get("channelList");
                    if (channelList != null && !channelList.isEmpty()) {
                        boolean isMatched = channelList.stream()
                                .allMatch(channel -> cameraType.equals(channel.get("type")));
                        if (!isMatched) {
                            // 设置特定的错误码和消息，不返回具体相机通道信息
                            return Map.of(
                                    "resCode", -1, // 自定义错误码
                                    "resMsg", "请添加正确接入类型的相机" // 自定义错误信息
                            );
                        }
                    }
                }*/
                // 检查是否有 resData 和 channelList
                if ("0".equals(responseBody.get("resCode").toString())) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> resData = (Map<String, Object>) responseBody.get("resData");
                    List<Map<String, Object>> channelList = (List<Map<String, Object>>) resData.get("channelList");

                    // 如果选择了特定类型的相机（非默认），则进行匹配验证
                    if (cameraType != null && cameraType != 0 && channelList != null && !channelList.isEmpty()) {
                        boolean isMatched = channelList.stream()
                                .allMatch(channel -> cameraType.equals(channel.get("type")));
                        if (!isMatched) {
                            return Map.of(
                                    "resCode", -1,
                                    "resMsg", "请添加正确接入类型的相机"
                            );
                        }
                    }
                }

                return responseBody; // 返回完整的响应体
            } else {
                throw new RuntimeException("查询相机通道号失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 查询相机信息
     * * @author xhl
     * @param token
     * @return
     */
    public Map<String, Object> queryCameraList(String token, Integer cameraType, String cameraId) {
        String url = baseUrl + "queryCameraList";
        // 创建请求头，包括必要的授权信息
        HttpHeaders headers = new HttpHeaders();
        headers.set("Token" , token);
        headers.set("Content-Type", "application/json"); // 添加内容
        headers.set("pageNum", "1");
        headers.set("pageSize", "10");
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (cameraType != null) {
            builder.queryParam("cameraType", cameraType);
        }
        if (cameraId != null) {
            builder.queryParam("cameraId", cameraId);
        }

        HttpEntity<?> entity = new HttpEntity<>(headers);
        try {
            ResponseEntity<Map> response = restTemplate.exchange(
                    builder.toUriString(),
                    HttpMethod.GET,
                    entity,
                    Map.class
            );
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody(); // 返回完整的响应体
            } else {
                throw new RuntimeException("查询相机信息失败，HTTP状态码：" + response.getStatusCodeValue());
            }
        }catch (Exception e){
            logger.error("查询相机列表时发生错误: {}", e.getMessage(), e);
            throw new RuntimeException("查询相机信息失败", e);
        }
    }
    /**
     * 添加和更新相机信息
     * * @author xhl
     * @param token
     * @return
     */
    /*public Map<String, Object> modifyCamera(String token) {
        String url = baseUrl + "modifyCamera";
        // 创建请求头，包括必要的授权信息
        HttpHeaders headers = new HttpHeaders();
        headers.set("Token" , token);
        headers.set("Content-Type", "application/json"); // 添加内容

    }*/
    /**
     * 查询人脸库信息
     * * @author xhl
     * @param token
     * @return
     */
    public Map<String, Object> queryFaceLibInfo(String token) {
        String url = baseUrl + "queryFaceLibInfo";

        // 创建请求头，包括必要的授权信息
        HttpHeaders headers = new HttpHeaders();
        headers.set("Token" , token);
        headers.set("Content-Type", "application/json"); // 添加内容
        headers.set("cameraId", "MV2447510365010094");
        headers.set("taskType", "");
        headers.set("faceLibName", "");
        headers.set("pageNum", "1");
        headers.set("pageSize", "10");

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(null, headers);

        try {
            ResponseEntity<Map> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    Map.class
            );
            if (response.getStatusCode().is2xxSuccessful()) {
                return response.getBody(); // 返回完整的响应体
            } else {
                throw new RuntimeException("查询人脸库信息失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.info(e.getMessage());
        }
    return null;
    }
}